from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QTableWidgetItem, QApplication
from PyQt5.QtCore import QTranslator
from classes.engine import Engine
from ui_py.page4_ui import Main_Ui
from temp import Excel, ReadExcel
from validation import validation
from error import Error
import json
from expert import Expert
from dataExpert import Data
class Page4(QtWidgets.QWidget, Main_Ui):
    engine = Engine()
    flag = 0
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.setupUi(self)
        with open('lang.json', encoding='utf-8') as file:
            data = json.load(file)
        if data['lang'] != "":
            self.trans = QTranslator(self)
            self.trans.load('translate/' + 'page4')
            _app = QApplication.instance() # получить экземпляр приложения
            _app.installTranslator(self.trans)
        self.conmass = 0
        self.n = 5
        self.err = Error()
        self.expert = Expert()
        self.data = Data()
        self.err.clear = 0
        if data['lang'] != "":
            page = data['en']['page4']
            self.comboBox.addItem(page['conmass'])
            self.comboBox.setCurrentText(page['conmass'])
            self.comboBox.addItem(page['conmass_one'], 1)
            self.comboBox.addItem(page['conmass_two'], 2)
        else:
            self.comboBox.addItem("Выберите способ")
            self.comboBox.setCurrentText("Выберите способ")
            self.comboBox.addItem("Приведенные к радиусам кривошипа", 1)
            self.comboBox.addItem("Неуравновешенные силы", 2)
        self.comboBox.currentIndexChanged.connect(self.handleActivated)
        try:
            self.comboBox.blockSignals(True)
            self.conmass = self.data.excel['Conmass']
            if self.conmass == 1:
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.comboBox.setCurrentText(page['conmass_one'])
                else:
                    self.comboBox.setCurrentText("Приведенные к радиусам кривошипа")
            elif self.conmass == 2:
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.comboBox.setCurrentText(page['conmass_two'])
                else:
                    self.comboBox.setCurrentText("Неуравновешенные силы")
            self.comboBox.blockSignals(False)
        except:
            pass
        self.tableWidget.blockSignals(True)
        if self.engine.cil == "L6" or self.engine.cil == "V12":
            self.n = 8
        elif self.engine.cil == "L4" or self.engine.cil == "V8":
            self.n = 6
        if self.conmass == 1:
            while (self.tableWidget.rowCount() > 0):
                self.tableWidget.removeRow(0)
            while (self.tableWidget.columnCount() > 0):
                self.tableWidget.removeColumn(0)
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Data"))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Данные"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Единицы измерения"))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Unit"))
            for i in range(1, self.n):
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][0].format(i, i)))
                else: 
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Масса, приведенная к радиусу кривошипа, действующая на шейку {0}-го коренного подшипника; mk{1}".format(i, i)))
                try:
                    value = str(self.data.excel['mk{0}'.format(i)])
                except:
                    value = ""
                self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
                if data['lang'] != "":
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('kg'))
                else:
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('кг'))
            for i in range(1, self.n):
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][1].format(i, i)))
                else:
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения массы {0}; delt{1}".format(i, i)))
                try:
                    value = str(self.data.excel['delt{0}'.format(i)])
                except:
                    value = ""
                self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
                if data['lang'] != "":
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
                else:
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))
        elif self.conmass == 2:
            while (self.tableWidget.rowCount() > 0):
                self.tableWidget.removeRow(0)
            while (self.tableWidget.columnCount() > 0):
                self.tableWidget.removeColumn(0)
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][2]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Номер"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][3]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Момент W*R"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][4]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Осевое положение"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][5]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Угол установки"))
            for i in range(1, self.n-1):
                for j in range(1, 7):
                    row = self.tableWidget.rowCount()
                    self.tableWidget.insertRow(row)
                    if data['lang'] != "":
                        page = data['en']['page4']
                        self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][6].format(j)))
                        self.tableWidget.setItem(row, 0, QTableWidgetItem(page['table'][7].format(i, i+1)))
                    else:
                        self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Неуравновешенная масса №{0}".format(j)))
                        self.tableWidget.setItem(row, 0, QTableWidgetItem('{0} и {1} коренная шейка'.format(i, i+1)))
                    try:
                        value = str(self.data.excel['WR{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 1, QTableWidgetItem(value))
                    try:
                        value = str(self.data.excel['R{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 2, QTableWidgetItem(value))
                    try:
                        value = str(self.data.excel['delt{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 3, QTableWidgetItem(value))
        self.tableWidget.blockSignals(False)
        self.tableWidget.cellChanged.connect(self.cellChange)
    def handleActivated(self, index):
        with open('lang.json', encoding='utf-8') as file:
            data = json.load(file)
        self.tableWidget.blockSignals(True)
        if self.engine.cil == "L6" or self.engine.cil == "V12":
            self.n = 8
        elif self.engine.cil == "L4" or self.engine.cil == "V8":
            self.n = 6
        self.conmass = self.comboBox.currentData()
        self.expert.excel['Conmass'] = self.conmass
        self.data.excel['Conmass'] = self.conmass
        # self.excel.updateCell('Conmass', self.conmass, self.filename)
        if self.conmass == 1:
            while (self.tableWidget.rowCount() > 0):
                self.tableWidget.removeRow(0)
            while (self.tableWidget.columnCount() > 0):
                self.tableWidget.removeColumn(0)
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Data"))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Данные"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Unit"))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Единицы измерения"))
            for i in range(1, self.n):
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][0].format(i, i)))
                else:
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Масса, приведенная к радиусу кривошипа, действующая на шейку {0}-го коренного подшипника; mk{1}".format(i, i)))
                try:
                    value = str(self.data.excel['mk{0}'.format(i)])
                except:
                    value = ""
                self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
                if data['lang'] != "":
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('kg'))
                else:
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('кг'))
            for i in range(1, self.n):
                row = self.tableWidget.rowCount()
                self.tableWidget.insertRow(row)
                if data['lang'] != "":
                    page = data['en']['page4']
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][1].format(i, i)))
                else:
                    self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Угол расположения массы {0}; delt{1}".format(i, i)))
                try:
                    value = str(self.data.excel['delt{0}'.format(i)])
                except:
                    value = ""
                self.tableWidget.setItem(row, 0, QTableWidgetItem(value))
                if data['lang'] != "":
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('deg'))
                else:
                    self.tableWidget.setItem(row, 1, QTableWidgetItem('град'))
        else:
            while (self.tableWidget.rowCount() > 0):
                self.tableWidget.removeRow(0)
            while (self.tableWidget.columnCount() > 0):
                self.tableWidget.removeColumn(0)
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][2]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Номер"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][3]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Момент W*R"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][4]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Осевое положение"))
            column = self.tableWidget.columnCount()
            self.tableWidget.insertColumn(column)
            if data['lang'] != "":
                page = data['en']['page4']
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem(page['table'][5]))
            else:
                self.tableWidget.setHorizontalHeaderItem(column, QTableWidgetItem("Угол установки"))
            for i in range(1, self.n-1):
                for j in range(1, 7):
                    row = self.tableWidget.rowCount()
                    self.tableWidget.insertRow(row)
                    if data['lang'] != "":
                        page = data['en']['page4']
                        self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem(page['table'][6].format(j)))
                        self.tableWidget.setItem(row, 0, QTableWidgetItem(page['table'][7].format(i, i+1)))
                    else:
                        self.tableWidget.setVerticalHeaderItem(row, QTableWidgetItem("Неуравновешенная масса №{0}".format(j)))
                        self.tableWidget.setItem(row, 0, QTableWidgetItem('{0} и {1} коренная шейка'.format(i, i+1)))
                    try:
                        value = str(self.data.excel['WR{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 1, QTableWidgetItem(value))
                    try:
                        value = str(self.data.excel['R{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 2, QTableWidgetItem(value))
                    try:
                        value = str(self.data.excel['delt{0}{1}'.format(i, j)])
                    except:
                        value = ""
                    self.tableWidget.setItem(row, 3, QTableWidgetItem(value))
        self.tableWidget.blockSignals(False)
    def cellChange(self, row, column):
        wr, r, delt = "", "", ""
        arr = [[0, 5], [6, 11], [12, 17], [18, 23], [24, 29], [30, 35]]
        for i in range(len(arr)):
            if row >= arr[i][0] and row <= arr[i][1]:
                wr = "WR{0}{1}".format(i+1, (row % 6) + 1)
                r = "R{0}{1}".format(i+1, (row % 6) + 1)
                delt = "delt{0}{1}".format(i+1, (row % 6) + 1)
                break
        if self.conmass == 2:
            if column == 1:
                if validation(self.tableWidget.item(row, column).text(), wr, self.data.excel):
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(112, 255, 127))
                    self.tableWidget.blockSignals(False)
                    # self.excel.updateCell(wr, self.tableWidget.item(row, column).text(), self.filename)
                    self.data.excel[wr] = self.tableWidget.item(row, column).text()
                    self.expert.excel[wr] = self.tableWidget.item(row, column).text()
                    try:
                        if self.err.error_dict[key] > 0:
                            del self.err.error_dict[key]
                    except:
                        pass
                else:
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(255, 152, 152))
                    self.tableWidget.blockSignals(False)
                    self.err.error_dict[key] = 4
                    self.err.page = 4
            elif column == 2:
                if validation(self.tableWidget.item(row, column).text(), r, self.data.excel):
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(112, 255, 127))
                    self.tableWidget.blockSignals(False)
                    # self.excel.updateCell(r, self.tableWidget.item(row, column).text(), self.filename)
                    self.data.excel[r] = self.tableWidget.item(row, column).text()
                    self.expert.excel[r] = self.tableWidget.item(row, column).text()
                    try:
                        if self.err.error_dict[key] > 0:
                            del self.err.error_dict[key]
                    except:
                        pass
                else:
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(255, 152, 152))
                    self.tableWidget.blockSignals(False)
                    self.err.error_dict[key] = 4
                    self.err.page = 4
            elif column == 3:
                if validation(self.tableWidget.item(row, column).text(), delt, self.data.excel):
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(112, 255, 127))
                    self.tableWidget.blockSignals(False)
                    # self.excel.updateCell(delt, self.tableWidget.item(row, column).text(), self.filename)
                    self.data.excel[delt] = self.tableWidget.item(row, column).text()
                    self.expert.excel[delt] = self.tableWidget.item(row, column).text()
                    try:
                        if self.err.error_dict[key] > 0:
                            del self.err.error_dict[key]
                    except:
                        pass
                else:
                    self.tableWidget.blockSignals(True)
                    self.tableWidget.item(row, column).setBackground(QtGui.QColor(255, 152, 152))
                    self.tableWidget.blockSignals(False)
                    self.err.error_dict[key] = 4
                    self.err.page = 4

        else:
            key = self.tableWidget.verticalHeaderItem(row).text().split('; ')[1]
            if validation(self.tableWidget.item(row, column).text(), key, self.data.excel):
                self.tableWidget.blockSignals(True)
                self.tableWidget.item(row, column).setBackground(QtGui.QColor(112, 255, 127))
                self.tableWidget.blockSignals(False)
                self.expert.excel[key] = self.tableWidget.item(row, column).text()
                self.data.excel[key] = self.tableWidget.item(row, column).text()
                # self.excel.updateCell(key, self.tableWidget.item(row, column).text(), self.filename)
                try:
                    if self.err.error_dict[key] > 0:
                        del self.err.error_dict[key]
                except:
                    pass
            else:
                self.tableWidget.blockSignals(True)
                self.tableWidget.item(row, column).setBackground(QtGui.QColor(255, 152, 152))
                self.tableWidget.blockSignals(False)
                self.err.error_dict[key] = 4
                self.err.page = 4
    # def press(self, row, column):
    #     self.tableWidget.cellChanged.connect(self.cellChange)